package top.market.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yungouos.pay.wxpay.WxPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import top.market.config.WxPayConfig;
import top.market.model.entity.*;
import top.market.mapper.OrdersMapper;
import top.market.model.vo.OrderPaymentVO;
import top.market.model.vo.Result;
import top.market.service.IAddressBookService;
import top.market.service.IOrderDetailService;
import top.market.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.market.service.IShoppingCartService;
import top.market.util.CurrentUserUtil;
import top.market.util.WeChatPayUtil;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author li yuhai
 * @since 2025-03-26
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    @Autowired
    private IAddressBookService addressBookService;
    @Autowired
    private IShoppingCartService shoppingCartService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Override
    @Transactional
    public Orders yungouosNativePayOrder(Orders order) {
        // 判断地址
        LambdaQueryWrapper<AddressBook> addressQuery = new LambdaQueryWrapper<>();
        addressQuery.eq(AddressBook::getId, order.getAddressBookId()).eq(AddressBook::getUserId, CurrentUserUtil.getCustomUserDetails().getId());
        AddressBook addressBook = addressBookService.getOne(addressQuery);
        if (addressBook == null) {
            return null;
        }
        // 填充信息
        order.setUserId(CurrentUserUtil.getCustomUserDetails().getId());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(OrderStatusEnum.PENDING_PAYMENT.getCode());
        // 统计金额
        LambdaQueryWrapper<ShoppingCart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cartLambdaQueryWrapper.eq(ShoppingCart::getUserId, CurrentUserUtil.getCustomUserDetails().getId());
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(cartLambdaQueryWrapper);
        BigDecimal amount = BigDecimal.ZERO;
        for (ShoppingCart shoppingCart : shoppingCartList) {
            amount = amount.add(shoppingCart.getAmount());
        }
        order.setAmount(amount);
        order.setPhone(addressBook.getPhone());
        order.setConsignee(addressBook.getConsignee());
        order.setAddress(addressBook.getDetail());
        int insert = baseMapper.insert(order);
        if (insert > 0) {
            // 订单详情信息创建
            List<OrderDetail> orderDetailList = new ArrayList<>();
            for (ShoppingCart shoppingCart : shoppingCartList) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setName(shoppingCart.getName());
                orderDetail.setImage(shoppingCart.getImage());
                orderDetail.setOrderId(order.getId());
                orderDetail.setProductTypeValue(shoppingCart.getProductTypeValue());
                orderDetail.setNumber(shoppingCart.getNumber());
                orderDetail.setAmount(shoppingCart.getAmount());
                orderDetailList.add(orderDetail);
            }
            boolean b = orderDetailService.saveBatch(orderDetailList);
            if (!b) throw new RuntimeException("订单详情信息创建失败");
        }
        return insert > 0 ? order : null;
    }

    // 原生微信支付功能
    @Override
    @Transactional
    public Map nativePayOrder(Orders order) {
        // 判断地址
        LambdaQueryWrapper<AddressBook> addressQuery = new LambdaQueryWrapper<>();
        addressQuery.eq(AddressBook::getId, order.getAddressBookId()).eq(AddressBook::getUserId, CurrentUserUtil.getCustomUserDetails().getId());
        AddressBook addressBook = addressBookService.getOne(addressQuery);
        if (addressBook == null) {
            return null;
        }
        // 填充信息
        order.setUserId(CurrentUserUtil.getCustomUserDetails().getId());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(OrderStatusEnum.PENDING_PAYMENT.getCode());
        // 统计金额
        LambdaQueryWrapper<ShoppingCart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cartLambdaQueryWrapper.eq(ShoppingCart::getUserId, CurrentUserUtil.getCustomUserDetails().getId());
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(cartLambdaQueryWrapper);
        BigDecimal amount = BigDecimal.ZERO;
        for (ShoppingCart shoppingCart : shoppingCartList) {
            amount = amount.add(shoppingCart.getAmount());
        }
        order.setAmount(amount);
        order.setPhone(addressBook.getPhone());
        order.setConsignee(addressBook.getConsignee());
        order.setAddress(addressBook.getDetail());
        int insert = baseMapper.insert(order);
        if (insert > 0) {
            // 订单详情信息创建order_detail表插入信息
            List<OrderDetail> orderDetailList = new ArrayList<>();
            for (ShoppingCart shoppingCart : shoppingCartList) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setName(shoppingCart.getName());
                orderDetail.setImage(shoppingCart.getImage());
                orderDetail.setOrderId(order.getId());
                orderDetail.setProductTypeValue(shoppingCart.getProductTypeValue());
                orderDetail.setNumber(shoppingCart.getNumber());
                orderDetail.setAmount(shoppingCart.getAmount());
                orderDetail.setProductId(shoppingCart.getProductId());
                orderDetailList.add(orderDetail);
            }
            boolean b = orderDetailService.saveBatch(orderDetailList);
            if (!b) throw new RuntimeException("订单详情信息创建失败");
            // 删除购物车信息
            List<Long> ids = shoppingCartList.stream().map(ShoppingCart::getId).collect(Collectors.toList());
            shoppingCartService.removeBatchByIds(ids);
        } else throw new RuntimeException("订单创建失败");
        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = null;
        try {
//            jsonObject = weChatPayUtil.pay(
//                    order.getNumber(), //商户订单号
//                    order.getAmount(), //支付金额，单位 元
//                    "商品描述", //商品描述
//                    CurrentUserUtil.getCustomUserDetails().getOpenid() //微信用户的openid
//            );
            jsonObject = weChatPayUtil.moniPay(
                    order.getNumber(), //商户订单号
                    order.getAmount(), //支付金额，单位 元
                    "商品描述", //商品描述
                    CurrentUserUtil.getCustomUserDetails().getOpenid() //微信用户的openid
            );
        } catch (Exception e) {
            throw new RuntimeException("微信支付下单失败");
        }
        Map javaObject = jsonObject.toJavaObject(Map.class);
        //  OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        //  vo.setPackageStr(jsonObject.getString("package"));
        return javaObject;
    }



}
